# -*- coding: utf-8 -*-
from datetime import timedelta
from time import time
from utils.operators.rich_sql_sensor import RichSqlSensor
from jms.dm.dm_report_site_errscan_detail_dt_sum import jms_dm__dm_report_site_errscan_detail_dt_sum
#doris表名
doris_table = "dwd_report_site_errscan_detail_dt_sum"
#label名
label = f"{doris_table}_{int(time())}"
#hive中表名
hive_table = "dm_report_site_errscan_detail_dt_sum"
#hdfs文件路径
hdfs_path ="hdfs://{{var.value.hadoop_namespace}}/dw/hive/jms_dm.db/external/"
timeout = timedelta(hours=2).seconds
#判断当天分区是否存在
file_path = f'"{hdfs_path}{hive_table}/dt={{{{ execution_date | cst_ds }}}}/*"'
partition_lists = []
path_lists = []
for i in range(0, 1):
    if i == 0:
        partition_lists.append("p{{ execution_date | cst_ds_nodash }}")
        path_lists.append(file_path)
    else:
        partition_lists.append("p{{ execution_date | date_add(-" + str(i) + ") | cst_ds_nodash }}")
        path_lists.append(f'"{hdfs_path}{hive_table}/dt={{{{ execution_date | date_add(-{i}) | cst_ds }}}}/*"')

partition_str = ",".join(partition_lists)
path_str = ",".join(path_lists[::-1])
doris_jms_dwd__dwd_report_site_errscan_detail_dt_sum = RichSqlSensor(
    task_id='doris_jms_dwd__dwd_report_site_errscan_detail_dt_sum',
    pool='broker_load_pool',
    email=['macheng@jtexpress.com','yl_bigdata@yl-scm.com'],
    task_concurrency=1,
    conn_id='doris',
    pre_sql=f"""
                 TRUNCATE TABLE jms_dwd.{doris_table} PARTITION ({partition_str});
                 LOAD LABEL jms_dwd.{label} (
                     DATA INFILE({path_str})
                     INTO TABLE {doris_table}
                     FORMAT AS 'PARQUET'
                 )
                 WITH BROKER '{{{{ var.json.doris_brokers | random_choice }}}}'
                 PROPERTIES ('timeout'='{timeout}', 'max_filter_ratio'='0.0')""",
    poke_sql=f"SHOW LOAD FROM jms_dwd WHERE label = '{label}' ORDER BY CreateTime DESC LIMIT 1",
    sql_on_kill=f"CANCEL LOAD FROM jms_dwd WHERE LABEL = '{label}'",
    success=lambda r: r[2] == 'FINISHED',
    failure=lambda r: (r[2] is not None and r[2] == 'CANCELLED', str(r[7])),
    poke_interval=60,
    #execution_timeout=timedelta(seconds=timeout + 120)
    #excel平均时长:1分6秒
    execution_timeout = timedelta(minutes=30), )

doris_jms_dwd__dwd_report_site_errscan_detail_dt_sum << [jms_dm__dm_report_site_errscan_detail_dt_sum]
        
        
        